// pages/detail/index.js
var util = require('../../utils/util.js')
let mmssArr = util.generateTimeArr(60);
let hhArr = util.generateTimeArr(12);
let inTimer = null;
var CONFIG = require("../../utils/config.js")
var that;

const app = getApp()
var Interval
Page({

  /**
   * 页面的初始数据
   */
  data: {
    contentBook: '',
    bookid: '',
    status: false,
    zan: false,
    content: {},
    systemSay: {},
    myrole: {},
    talker: {},
    pageSize: 2,
    result: {},
    count: '',
    toView: 'red',
    scrollTop: 10000,
    isaotu: false,
    tid: 1,
    zhang: 1,
    animationData: {},
    Timeshow: true,
    has_pay: false,
    has_share: false,
    hh: 0,
    mm: 1,
    ss: 59,
    hhArr: hhArr,
    mmArr: mmssArr,
    ssArr: mmssArr,
    timeInSecond: 0,
    displayTime: '00:00',
    time: 0,
    process: 0,
    nextface: '',
    isNext: false,
    allPage: 1,
    viewInfo: 0,
    NextBook: {},
    animationData: {},

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    var bookid = options.id
    var content = options.content
    var viewInfo = options.viewInfo
    var process = options.process
    var face = options.face

    wx.setNavigationBarTitle({
      title: app.globalData.booktitle
    });
    var uid = wx.getStorageSync('openId')
    var zhang = viewInfo;
    console.log("一开始的zhangjie是" + zhang)
    var views = viewInfo - 1;
    if (uid) {
      that.getContent(content, views);


      console.log("正在测试1")

      that.setData({
        bookid: bookid,
        zhang: viewInfo,
        process: process,
        nextface: face,
        viewInfo: views,
        contentBook: content
      })
    }
    that.addHistory(uid, bookid, zhang);
  },

  addHistory: function (uid, bookid, zhang) {
    var that = this
    var url = CONFIG.URL.addHistory
    var data = {
      "wxuid": uid,
      "bookid": bookid,
      "zhang": zhang
    };
    CONFIG.post_from(url, data, function (res) {
      console.log(res)
      console.log("上传数据成功" + zhang)

      var process = that.data.process
      that.updateProcess(bookid, zhang, process)
    }, function (err) {
      console.log("400")
    })
  },
  updateProcess: function (bookid, zhang, process) {
    var that = this
    var url = CONFIG.URL.updateProcess
    var uid = wx.getStorageSync('openId')
    wx.request({
      url: url,
      data: {
        "wxuid": uid,
        "bookid": bookid,
        "zhang": zhang,
        "process": process
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      success: function (res) {
        console.log(res)
        console.log("上传数据成功2")
      },
      faile: function (err) {
        console.log(err)
        console.log("上传数据shibai")
      }
    })

  },
  getContent: function (content, viewInfo) {
    var that = this
    var url = CONFIG.URL.books + content//得到数据
    wx.request({
      url: url,
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'GET',
      success: function (res) {
        let reg = new RegExp('\\[img\\](.+)\\[\\/img\\]');


        var myrole = res.data.myrole
        var roles = res.data.roles
        var rlength = roles.length
        console.log(viewInfo)
        console.log("getconte的长度" + rlength)
        var content = res.data.content[viewInfo]
        var clength = content.length
        var process = that.data.process
        if (process > 100) {
          process = 95;
        }
        var pageSize = parseInt(clength * (process / 100))
        console.log(pageSize)
        if (pageSize < 2) {
          pageSize = 1
        }
        console.log("====112===")
        console.log(clength)

        for (var i = 0; i < rlength; i++) {
          for (var j = 0; j < clength; j++) {
            if (content[j].name == roles[i].name) {

              content[j].head = roles[i].head
              if (content[j].name == myrole) {

                var myinfo = roles[i]

              }
            }
            if (reg.test(content[j].body)) {
              content[j].img = content[j].body.replace(reg, '$1');
              content[j].body = '';

            }

          }
        }


        that.setData({
          result: content,
          myrole: myinfo,
          count: clength,
          pageSize: pageSize,
          allPage: res.data.content.length
        })
        that.pageShow(res.data.content[viewInfo]);



      },
      fail: function (err) {

        console.log(err)
      }
    })
  },

  updatestore: function (e) {
    var that = this
    var status = that.data.status
    var bookid = that.data.bookid
    if (status == false) {
      var uid = wx.getStorageSync('openId')
      var url = CONFIG.URL.updatestore//收藏
      var data = {
        "wxuid": uid,
        "bookid": bookid
      };
      CONFIG.post_from(url, data, function (res) {
        console.log("上传成功")
        console.log(res)
        that.setData({
          status: true
        })
      }, function (err) {
        console.log(err)
      })
    } else {
      return;
    }

  },

  updatezan: function (e) {
    var that = this
    var zan = that.data.zan
    var bookid = that.data.bookid
    var uid = wx.getStorageSync('openId')
    if (zan == false) {
      console.log("bookid是" + bookid)
      var url = CONFIG.URL.updatezan
      var data = {
        "wxuid": uid,
        "bookid": bookid
      };
      CONFIG.post_from(url, data, function (res) {
        console.log("上传成功")
        console.log(res)
        that.setData({
          zan: true
        })
      }, function (err) {
        console.log(err)
      })
    } else {
      return;
    }
  },

  querybookById: function (id) {
    var that = this

    var url = CONFIG.URL.querybookById
    var data = {
      "id": id
    };
    CONFIG.post_from(url, data, function (res) {
      console.log("200")
      console.log(res.data[0])
      if (res.statusCode == 200) {
        that.setData({
          NextBook: res.data[0],

        })
      }
    }, function (err) {
      console.log(err)
    })
  },
  ReStart: function (e) {
    console.log(e)
    var that = this
    that.setData({
      pageSize: 0,
      isNext: false,
      pageSize: 1
    })
    that.clickMe();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  closer: function (e) {
    console.log(e)
    var that = this
    that.setData({
      Timeshow: true,
      has_share: true,
    })
  },
  clickMe: function () {
    var that = this
    var pageSize = that.data.pageSize
    var count = that.data.count
    var content = that.data.result
    var has_share = that.data.has_share
    var zhang = that.data.zhang
    var allPage = that.data.allPage

    console.log("全部页数是" + allPage)
    console.log(zhang)
    if (has_share == true) {
      that.setData({
        Timeshow: false,
      })
      that.stopRead();
      return;
    }
    if (pageSize < count) {
      that.setData({
        pageSize: ++pageSize,

      });


      that.pageShow(content);
    } else {
      var bookid = that.data.bookid

      if (zhang < allPage) {
        that.setData({
          isNext: true
        })

        that.querybookById(bookid);
        that.opcShow();
        that.stopRead();

      } else {
        that.setData({
          isNext: false
        })
      }
      return;
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    // that.pageShow();

  },
  opcShow: function () {
    var animation = wx.createAnimation({
      duration: 1200,
      timingFunction: 'ease-out',
    })
    this.animation = animation


    animation.translateY(-45).step()
    this.setData({
      animationData: animation.export()
    })

  },

  onSetHandler() {

    var that = this
    console.log(util.getHHSSMM(1))
    that.setData({
      timeInSecond: util.getTotalSeconds(that.data.hh, that.data.mm, that.data.ss),
      //displayTime: util.getHHSSMM(this.data.timeInSecond)
    });
    that.setData({
      //timeInSecond: util.getTotalSeconds(this.data.hh, this.data.mm, this.data.ss),
      displayTime: util.getHHSSMM(that.data.timeInSecond)
    })

  },
  onStartHandler() {
    if ((!inTimer) && (this.data.timeInSecond != 0)) {


      this.setData({
        action: {
          method: 'pause'
        }
      })
      inTimer = setInterval(() => {
        this.setData({
          timeInSecond: this.data.timeInSecond - 1
        })
        this.setData({

          displayTime: util.getHHSSMM(this.data.timeInSecond)
        })
        if (this.data.timeInSecond <= 0) {

          this.setData({
            Timeshow: true,
            has_share: false
          })
          clearInterval(inTimer);
          inTimer = null;

          this.setData({
            action: {
              method: 'play'
            }
          })
        }
      }, 1000)
    } else {
      console.log('interval', inTimer)
    }

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  //分页数据显示
  pageShow: function (dataArr) {
    var that = this
    // var dataArr = that.data.result
    var pageNo = 1;

    var pageSize = that.data.pageSize
    var content = that.data.content
    var count = that.data.count
    var process = that.data.process
    if (pageSize <= count) {
      var res = that.pagination(pageNo, pageSize, dataArr);
      console.log(res)

      console.log("数据测试中")
      console.log(pageSize)
      if (res) {
        if (res[pageSize - 1].name == "管理员" && res[pageSize - 1].body == "付费") {

          that.setData({
            Timeshow: false,
            has_share: true
          })
          that.stopRead();
          that.onSetHandler();
          that.onStartHandler();

        } else {
          var winHeight = that.data.winHeight
          var scrollTop = that.data.scrollTop
          that.setData({
            content: res,
            scrollTop: scrollTop + 1000,

          })

        }
      } else {
        console.log("=====hahha res数据了")
      }
    } else {
      console.log("没有数据了哦")
      that.stopRead();

      clearInterval(Interval)
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this
    var pageSize = that.data.pageSize
    var count = that.data.count
    console.log("count总数:" + count)
    console.log(pageSize)
    var nums = Math.ceil((pageSize / count) * 100)
    console.log("最后的page是" + nums)
    if (nums > count) {
      nums = count - 1
    }
    clearInterval(Interval)
    that.setData({
      isaotu: false
    })
    var bookid = that.data.bookid
    var zhang = that.data.zhang
    var process = nums
    if (process > 100) {
      process = 99;
    }
    console.log("最后退出时章节是" + zhang + "进度是" + process)
    that.updateProcess(bookid, zhang, process)
  },
  aotuRead: function (e) {
    var that = this
    console.log(e)
    var tid = e.currentTarget.dataset.tid
    var speedNum = app.globalData.speedNum
    console.log(speedNum)
    var time = 3000 / speedNum

    console.log("tid是" + tid)
    console.log("时间是" + time)

    if (tid == 1) {
      Interval = setInterval(that.clickMe, time);
      that.setData({
        tid: 2,
        isaotu: true
      })
    } else {
      console.log("tingxia")
      clearInterval(Interval)
      that.setData({
        tid: 1,
        isaotu: false
      })
    }
  },
  stopRead: function (e) {

    var that = this
    that.setData({
      tid: 1,
      isaotu: false
    })
    clearInterval(Interval)
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */

  nextPage: function (e) {

    console.log("正在测试")
    var that = this
    var bookid = that.data.bookid
    var content = that.data.contentBook
    console.log("bookid" + bookid)
    var zhang = parseInt(that.data.zhang)

    var process = 1
    that.setData({
      isNext: false,
      pageSize: 1
    })

    var uid = wx.getStorageSync('openId')

    var views = parseInt(zhang) + 1;
    console.log(views)
    if (uid) {
      wx.showLoading({
        title: '加载中..',
      })
      console.log("正在测试2")
      that.setData({
        bookid: bookid,
        zhang: views,
        process: process,
        viewInfo: zhang,
      })
    }
    setTimeout(function () {
      wx.hideLoading();
      that.getContent(content, zhang);
      that.addHistory(uid, bookid, views);
      that.clickMe();
    }, 800);


  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  pagination: function (pageNo, pageSize, array) {
    var offset = (pageNo - 1) * pageSize;//分页限制函数
    return (offset + pageSize >= array.length) ? array.slice(offset, array.length) : array.slice(offset, offset + pageSize);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '我在超好看的神经小说小程序上看书,你也来吧',
      path: '/pages/index/index',
      success: function (res) {
        // 转发成功
        that.setData({
          Timeshow: true,
          has_share: false
        })
      },
      fail: function (res) {
        // 转发失败
      }
    }
  }

})